def serial_int(n, bcount):
    '''
    serial_int(n, bcount) -> bytearray

    Serialize an integer 'n' to network byte order in 'bcount' bytes
    '''
    buf = bytearray()
    for i in range(bcount - 1, -1, -1):
        buf.append((n & (0xff << (8 * i))) >> (8 * i))
    return buf

def deserial_int(buf):
    '''
    deserial_int(buf) -> integer

    Deserialize a bytearray from network byte order to an integer
    '''
    n = 0
    for i in range(0, len(buf)):
        n <<= 8
        n |= buf[i]
    return n

def passPacket(packet, localIP, localPort, peerIP, peerPort, serial_int, deserial_int):
    '''
    Filter the packet.  Return True to drop the packet, False to pass the packet.

    Theese localIP, localPort, peerIP, peerPort indicate the information of the server socket
    '''
    if packet[14] != 8 or packet[15] != 0:  # Not IP protocol
        return False
    if packet[16] / 0x10 != 4:  # Not IPv4 protocol
        return False
    headLen = packet[16] % 0x10 * 4
    if packet[25] == 6:
        protocol = 'TCP'
    elif packet[25] == 17:
        protocol = 'UDP'
    else:   # Neither TCP nor UDP
        return False
    srcIP = deserial_int(packet[28 : 32])   # Get the source IP as an integer of the packet
    destIP = deserial_int(packet[32 : 36])   # Get the destination IP as an integer of the packet
    srcPort = deserial_int(packet[16 + headLen : 18 + headLen]) # Get the source port of the packet
    destPort = deserial_int(packet[18 + headLen : 20 + headLen])    # Get the destination port of the packet

    # You can customize your own filter logic below
    if protocol == 'TCP' and srcIP == localIP and srcPort == localPort:
        return False
    if protocol == 'TCP' and srcIP == peerIP and srcPort == peerPort:
        return False
    if protocol == 'TCP' and destIP == localIP and destPort == localPort:
        return False
    if protocol == 'TCP' and destIP == peerIP and destPort == peerPort:
        return False
    #if protocol != 'TCP':
    #    return False
    #if srcPort != 80 and destPort != 80:
    #    return False
    return True

# Set 'ret' to local variables so that the python source filter can get the result
try:
    ret = passPacket(packet, localIP, localPort, peerIP, peerPort, serial_int, deserial_int)
except Exception, e:
    print e
